package cn.daniel.framework.idgenerator.controller;

import cn.daniel.framework.idgenerator.common.Result;
import cn.daniel.framework.idgenerator.common.Status;
import cn.daniel.framework.idgenerator.exception.IdGeneratorServerException;
import cn.daniel.framework.idgenerator.service.IdGeneratorService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.List;

/**
 * @author daniel.tuen
 * @date 2025/9/16 16:10
 * @description
 */
@RestController
public class IdGeneratorController {

    @Autowired
    private IdGeneratorService idGeneratorService;

    @RequestMapping(value = "/api/snowflake/getId")
    public Long getSnowflakeId() {
        return get(idGeneratorService.getId());
    }

    @RequestMapping(value = "/api/snowflake/getIdList/{size}")
    public List<Long> getSnowflakeIdList(@PathVariable("size") int size) {
        if(size > 0 && size <= 1000){
            List<Long> idList = new ArrayList<>(size);
            for(int i = 0; i < size; i++){
                idList.add(get(idGeneratorService.getId()));
            }
            return idList;
        }
        throw new IdGeneratorServerException( "批量生成 ID 大小必须在 1-1000 之间，当前值：" + size);
    }

    private long get(Result result) {
        if (result.getStatus().equals(Status.EXCEPTION)) {
            throw new IdGeneratorServerException(result.toString());
        }
        return result.getId();
    }

}
